package org.dyndns.blackpaw.whirlmon;

import java.util.ArrayList;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
		TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
	static final String LOGTAG = "WHIRLMON";

	private TabHost mTabHost;
	private ViewPager mViewPager;
	private PagerAdapter mPagerAdapter;
	private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

	final class TabInfo {
		private final Class<?> clss;
		private final Bundle args;

		TabInfo(Class<?> _class, Bundle _args) {
			clss = _class;
			args = _args;
		}
	}

	/**
	 * A simple factory that returns dummy views to the Tabhost
	 * 
	 * @author mwho
	 */
	class TabFactory implements TabContentFactory {

		private final Context mContext;

		/**
		 * @param context
		 */
		public TabFactory(Context context) {
			mContext = context;
		}

		/**
		 * (non-Javadoc)
		 * 
		 * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
		 */
		public View createTabContent(String tag) {
			View v = new View(mContext);
			v.setMinimumWidth(0);
			v.setMinimumHeight(0);
			return v;
		}

	}

	public void addTab(String title, Class<?> clss, Bundle args) {
		TabHost.TabSpec tabSpec = mTabHost.newTabSpec(title);
		tabSpec.setIndicator(title);
		tabSpec.setContent(new TabFactory(this));
		mTabHost.addTab(tabSpec);

		mTabs.add(new TabInfo(clss, args));
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(LOGTAG, "onCreate");
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.main);

		// Initialise the TabHost
		initialiseTabHost(savedInstanceState);

		// Initialise ViewPager
		intialiseViewPager();

		// Start Monitor Service
		Intent intentSvc = new Intent(this, MainService.class);
		startService(intentSvc);

		if (savedInstanceState != null) {
			mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
		}
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
	 */
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString("tab", mTabHost.getCurrentTabTag()); // save the tab
																// selected
		super.onSaveInstanceState(outState);
	}

	/**
	 * Initialise the Tab Host
	 */
	private void initialiseTabHost(Bundle args) {
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
		addTab("Watched", WatchedFragment.class, null);
		addTab("News", NewsFragment.class, null);
		addTab("Recent", RecentFragment.class, null);
		mTabHost.setOnTabChangedListener(this);
	}

	/**
	 * Initialise ViewPager
	 */
	private void intialiseViewPager() {
		mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(),
				this);
		mViewPager = (ViewPager) super.findViewById(R.id.pager);
		mViewPager.setOffscreenPageLimit(3);
		mViewPager.setAdapter(this.mPagerAdapter);
		mViewPager.setOnPageChangeListener(this);
	}

	@Override
	protected void onDestroy() {
		Log.i(LOGTAG, "onDestroy");
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i(LOGTAG, "onResume");

		// Cancel any Notifications
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		mNotificationManager.cancel(MainService.ID_NM_NEW_MSG);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.i(LOGTAG, "onPause");

		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about: {
			Toast.makeText(this, getAppName() + " " + getAppVersion(),
					Toast.LENGTH_SHORT).show();
		}
			return true;

		case R.id.config:
			startActivity(new Intent(this, WhirlMonPreferencesActivity.class));
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	String getAppName() {
		try {
			int appId = getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.labelRes;
			String appName = getString(appId);
			return appName;
		} catch (Exception x) {
			return x.getMessage();
		}
	}

	String getAppVersion() {
		try {
			String versionName = getPackageManager().getPackageInfo(
					getPackageName(), 0).versionName;
			return versionName;
		} catch (Exception x) {
			return x.getMessage();
		}
	}

	/**
	 * The <code>PagerAdapter</code> serves the fragments when paging.
	 * 
	 * @author mwho
	 */
	public class PagerAdapter extends FragmentPagerAdapter {

		private FragmentActivity mContext;

		public PagerAdapter(FragmentManager fm, FragmentActivity context) {
			super(fm);
			mContext = context;
		}

		@Override
		public Fragment getItem(int position) {
			TabInfo info = mTabs.get(position);
			return Fragment.instantiate(mContext, info.clss.getName(),
					info.args);
		}

		@Override
		public int getCount() {
			return mTabs.size();
		}
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
	 */
	@Override
	public void onTabChanged(String tag) {
		// TabInfo newTab = this.mapTabInfo.get(tag);
		int pos = this.mTabHost.getCurrentTab();
		this.mViewPager.setCurrentItem(pos);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrolled
	 * (int, float, int)
	 */
	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.view.ViewPager.OnPageChangeListener#onPageSelected
	 * (int)
	 */
	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		this.mTabHost.setCurrentTab(position);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.view.ViewPager.OnPageChangeListener#
	 * onPageScrollStateChanged(int)
	 */
	@Override
	public void onPageScrollStateChanged(int state) {
		// TODO Auto-generated method stub

	}

}
